<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>部件列表</title>
    <!-- 引入 Element UI 的样式 -->
    <!-- <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" /> -->
    <link rel="stylesheet" href="../../assets/css/element-ui.css" />
    <link rel="stylesheet" href="../../assets/css/styles.css" />
      <!-- 引入阿里云OSS SDK -->
      <script src="../../assets/js/aliyun-oss-sdk-6.16.0.min.js"></script>
    <script src="../../assets/js/cdn.js"></script>
    <link rel="stylesheet" href="../../assets/fontawesome-free-6.7.2-web/css/all.min.css" />
  </head>
  <body>
    <div id="app">
      <lx-header slot="header" v-on:toggle="isToggle = !isToggle" :type="2"></lx-header>
      <div class="main-content">
        <div class="content" style="width: 100%">

          <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain size="mini" @click="handleAdd">新增</el-button>
                </el-col>
            </el-row>

          <div class="center-grid mb-20">
            <el-table v-loading="loading" :data="tableData">
                <el-table-column v-for="(item, index) in tableColumnData" :key="index" :label="item.fieldName" min-width="150" :width="item.width">
                    <template slot-scope="scope">
                      <template v-if="item.fieldApi==='componentUnit'">{{ getOptionsStr('base_component_unit',scope.row[item.fieldApi]) }}</template>
                      <template v-else> {{ scope.row[item.fieldApi] }} </template>
                    </template>
                  </el-table-column>
                <el-table-column label="操作" align="center" :resizable="false" :show-overflow-tooltip="false" width="180" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text"  @click="detailView(scope.row)">详情</el-button>
                        <el-button size="mini" type="text"  @click="handleUpdate(scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                v-show="total>0"
                :total="total"
                :current-page.sync="queryParams.pageNum"
                :page-size.sync="queryParams.pageSize"
                @current-change="getList"
            />
          </div>
        </div>
      </div>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" :fullscreen="true" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="部件编号" prop="componentCode">
                    <el-input v-model="form.componentCode" @input="handleInput" placeholder="请输入部件编号" :disabled="submitFlag === 1" />
                </el-form-item>
                <el-form-item label="部件名称" prop="componentName">
                    <el-input v-model="form.componentName" placeholder="请输入部件名称" />
                </el-form-item>
                <el-form-item label="供应商" prop="supplier">
                    <el-input v-model="form.supplier" placeholder="请输入供应商" />
                </el-form-item>
                <el-form-item label="单位" prop="componentUnit">
                  <el-select v-model="form.componentUnit" placeholder="请选择工具/工装类型" clearable>
                    <el-option v-for="(key,value) in optionsObj.base_component_unit" :key="value" :label="key" :value="value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="图片" prop="imgUrl">
                    <el-upload
                            :class="{disabled:eqObj.uploadDisabled}"
                            action="#"
                            :http-request="handleUpload"
                            :before-upload="beforeUpload"
                            :on-success="handleSuccess"
                            :on-error="handleError"
                            :file-list="fileList"
                            :limit="1"
                            :on-remove="handleRemove"
                            :on-change="handleLimit"
                            list-type="picture-card">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
    <script src="../../assets/js/constant.js"></script>
    <script src="../../assets/js/utils.js"></script>
    <script src="../../assets/js/auth.js"></script>
    <script src="../../assets/js/axios.min.js"></script>
    <!-- 引入 Vue.js -->
    <!-- <script src="https://unpkg.com/vue@2/dist/vue.js"></script> -->
    <script src="../../assets/js/vue.js"></script>
    <!-- 引入 Element UI 的 JS 文件 -->
    <!-- <script src="https://unpkg.com/element-ui/lib/index.js"></script> -->
    <script src="../../assets/js/element-ui.js"></script>

    <script type="module">
      import LxHeader from '../../pages/components/LxHeader/index.js'
      Vue.component('lx-header', LxHeader)
      checkAuthentication(2)
      new Vue({
        el: '#app',
        components: {},
        data() {
         return {
            currentUser: JSON.parse(localStorage.getItem('currentUser')) || {},
            userMenuList: JSON.parse(localStorage.getItem('userMenuList')) || [],
            businessCenters: [
                { name: '订单中心', path: '../index.html' },
                { name: '用户中心', path: '#' },
                { name: '产品中心', path: '#' },
                { name: '库存中心', path: '#' },
                { name: '财务中心', path: '#' },
                { name: '数据中心', path: '#' },
                { name: '系统中心', path: '#' },
                { name: '消息中心', path: '#' }
            ],
            queryParams: {
              pageNo: 1,
              pageSize: 10,
              puCode: '',
              puName: ''
            },
            total: 0,
            tableData: [],
            tableColumnData: [
              {
                fieldName: '部件编号',
                fieldApi: 'componentCode'
              },
              {
                fieldName: '部件名称',
                fieldApi: 'componentName'
              },
              {
                fieldName: '供应商',
                fieldApi: 'supplier'
              },
              {
                fieldName: '单位',
                fieldApi: 'componentUnit'
              },
              {
                fieldName: '创建时间',
                fieldApi: 'createTime'
              },
              {
                fieldName: '创建人',
                fieldApi: 'createBy'
              },
            ],
            // 遮罩层
            loading: true,
            dicts: ['base_component_unit'],
            optionsObj: [],
            // 选中数组
            componentCodes: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            submitFlag: 0,
            request_host: request_host,
            pageSizes: pageSizes,
            multipleSelection: [],
            ossConfig: ossConfig,
            fileList: [],
            eqObj: {
                uploadDisabled: false,
            },
          }
        },
        created() {
          this.getOptions()
          this.init()
        },
        methods: {
          exit,
          init() {
            this.getList()
          },
          getList() {
            this.loading = true
            try {
              axios.get(`${this.request_host}/system/component/list`,{ params: this.queryParams }).then((response) => {
                if (response.status == 200) {
                  this.tableData = response.data.rows
                  this.total = response.data.total
                  this.loading = false
                }
              })
            } catch (error) {
              console.error('请求失败:', error)
            }
          },
          handleInput(){
              this.form.componentCode = this.form.componentCode.toUpperCase().replace('－', '-');
          },
          getOptions() {
                this.dicts.forEach((item) => {
                    axios.get(`${this.request_host}/system/dict/data/type/${item}`).then((response) => {
                        this.$set(this.optionsObj, item, {})
                        if (response.status == 200) {
                            response.data.data.map((item1) => {
                                this.optionsObj[item][item1.dictValue] = item1.dictLabel
                            })
                        }
                    })
                })
            },
          /** 提交按钮 */
          submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.submitFlag == 0){
                      this.form.componentCode = this.form.componentCode.toUpperCase();
                        // 新增
                        axios.post(`${this.request_host}/system/component`, this.form)
                            .then(response => {
                                if (response.data.code == 200){
                                    this.$message.success("提交成功")
                                    this.cancel();
                                    this.getList()
                                }else {
                                    this.$message.error(response.data.msg)
                                }

                        })
                    }else{
                        //修改提交
                        axios.put(`${this.request_host}/system/component`, this.form)
                            .then(response => {
                                if (response.data.code == 200){
                                    this.$message.success("提交成功")
                                    this.cancel();
                                    this.getList();
                                }else {
                                    this.$message.error(response.data.msg)
                                }

                        })
                    }
                    const params = `componentCode=`+this.form.componentCode;
                    const url = `component_item.html?${params}`;
                    window.open(url, '_blank');
                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.form = {}
            this.fileList = []
        },
          handleQuery() {
            this.getList()
          },
          resetQuery() {
            this.queryParams = {
              pageNo: 1,
              pageSize: 10,
              puCode: '',
              puName: ''
            }
          },
          /** 新增按钮操作 */
          handleAdd() {
            this.resetQuery()
            this.open = true
            this.submitFlag = 0
            this.title = "添加部件"
          },
          /** 修改按钮操作 */
          handleUpdate(row) {
            this.resetQuery()
            const componentCode = row.componentCode || this.componentCodes[0]
            // 这里替换为实际的API调用
            axios.get(`${this.request_host}/system/component/` + componentCode)
                .then(response => {
                    this.form = response.data.data
                    console.log(this.form)
                    if (this.form.imgUrl) {
                        this.fileList = [{
                            name: this.form.imgUrl.split('/').pop(),
                            url: this.form.imgUrl
                        }];
                        this.eqObj.uploadDisabled = true;
                        this.$set(this.eqObj, 'uploadDisabled', true);
                    }
                    this.open = true
                    this.title = "修改部件"
                });
            this.submitFlag = 1

          },
          // 分页数量切换
          handleSizeChange(val) {
            this.$set(this.queryParams, 'pageSize', val)
            this.getData()
          },
          // 当前页码切换
          handleCurrentChange(val) {
            this.$set(this.queryParams, 'pageNo', val)
            this.getData()
          },
          detailView(row) {
            const componentCode = row.componentCode;
            const params = `componentCode=${encodeURIComponent(componentCode)}`;
            const url = `component_item.html?${params}`;
            window.open(url, '_blank');
          },
          getOptionsStr(opt, value) {
              if (this.optionsObj[opt] && value) {
                  return this.optionsObj[opt][value]
              }
              return ''
          },
          openMenu(url) {
            window.open(url)
          },
          handleLimit(file, fileList) {
              if (fileList.length >= 1) {
                  this.eqObj.uploadDisabled = true;
                  this.$set(this.eqObj, 'uploadDisabled', true);
              } else {
                  this.eqObj.uploadDisabled = false;
                  this.$set(this.eqObj, 'uploadDisabled', false);
              }
              this.$forceUpdate();
          },
            // 上传前校验
            beforeUpload(file) {
                const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isImage) {
                    this.$message.error('只能上传JPG/PNG格式的图片!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('图片大小不能超过2MB!');
                    return false;
                }
                return true;
            },
            // 处理上传
            handleUpload(options) {
                const file = options.file;
                const fileName = `component/${this.componentCode}/${Date.now()}-${file.name}`;

                try {
                    const client = new OSS({
                        accessKeyId: `${this.ossConfig.accessKeyId}`,
                        accessKeySecret: `${this.ossConfig.accessKeySecret}`,
                        bucket: `${this.ossConfig.bucketName}`,
                        endpoint: `${this.ossConfig.endpoint}`,
                        secure: true,
                        region: 'oss-cn-beijing',
                        timeout: 60000
                    });

                    // 使用普通上传
                    client.put(fileName, file).then(result => {
                        console.log('上传结果:', result);
                        if (result.res && result.res.status === 200) {
                            const fileUrl = `${this.ossConfig.outerUrl}/${fileName}`;
                            this.form.imgUrl = fileUrl;
                            //this.handleSuccess(fileUrl);
                        } else {
                            this.handleError(new Error('上传响应异常'));
                        }
                    }).catch(err => {
                        console.error('OSS上传失败:', err);
                        this.handleError(err);
                    });
                } catch (err) {
                    console.error('创建OSS客户端失败:', err);
                    this.handleError(err);
                }
            },
            // 上传成功回调
            handleSuccess(fileUrl) {
                // 更新文件列表
                this.fileList = [{
                    name: fileUrl.split('/').pop(),
                    url: fileUrl
                }];

                // 更新预览图片
                this.form.imgUrl = fileUrl;
            },
            handleRemove(file, fileList) {
                this.fileList = [];
                // 更新预览图片
                this.form.imgUrl = '';
                this.eqObj.uploadDisabled = false;
                this.$forceUpdate();
            },
            // 上传失败回调
            handleError(err) {
                console.error('上传失败:', err);
                let errorMsg = '上传失败';
                if (err.message) {
                    errorMsg += ': ' + err.message;
                }
                if (err.code) {
                    errorMsg += ` (错误代码: ${err.code})`;
                }
                this.$message.error(errorMsg);
            }
        }
      })
    </script>
    <style>
      .el-table th.el-table__cell {
        background-color: #f2f2f2; /* 例如，设置为浅灰色 */
      }
      .mb8 {
        margin-bottom: 10px;
    }
      .disabled .el-upload.el-upload--picture-card {
          display: none !important;
      }

      .disabled .el-button--success.is-plain {
          display: none !important;
      }
    </style>
  </body>
</html>
